import axios from 'axios';

// 生成简单的UUID（不依赖uuid包）
const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
};

// 配置基础 URL
// 使用 /api/enterprise 作为基础路径（企业端专用）
const API_BASE_URL = '/api/enterprise';

// 创建 axios 实例（企业端接口）
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  withCredentials: true,  // 重要！发送 Cookie（包含 token）
  headers: {
    'Content-Type': 'application/json',
  },
});

// 创建字典接口的 axios 实例（不在 /enterprise 下）
const dictClient = axios.create({
  baseURL: '/api',
  timeout: 10000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
});

/**
 * 获取指定期次的报表数据
 * @param {Object} params - { reporting_period: 'YYYY-MM' }
 * @returns {Promise<Object>} 报表数据
 */
export const fetchReport = async (params) => {
  try {
    const response = await apiClient.get('/report', { params });
    return response.data.data;  
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取报表失败');
  }
};

/**
 * 保存草稿
 * @param {Object} data - 报表表单数据
 * @returns {Promise<Object>}
 */
export const saveDraft = async (data) => {
  try {
    const response = await apiClient.post('/report/draft', data);
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '保存草稿失败');
  }
};

/**
 * 提交报表（带幂等键）
 * @param {Object} data - 报表表单数据
 * @returns {Promise<Object>}
 */
export const submitReport = async (data) => {
  try {
    // 自动生成幂等键（防重复提交）
    const idempotencyKey = generateUUID();
    const response = await apiClient.post('/report/submit', data, {
      headers: {
        'Idempotency-Key': idempotencyKey,
      },
    });
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '提交报表失败');
  }
};

/**
 * 获取减员类型字典（使用dictClient，路径：/api/dictionaries/*）
 * @returns {Promise<Array>}
 */
export const fetchReductionTypes = async () => {
  try {
    const response = await dictClient.get('/dictionaries/employment-reduction-types');
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取减员类型失败');
  }
};

/**
 * 获取减员原因字典（使用dictClient，路径：/api/dictionaries/*）
 * @returns {Promise<Array>}
 */
export const fetchReasons = async () => {
  try {
    const response = await dictClient.get('/dictionaries/employment-reduction-causes');
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取减员原因失败');
  }
};

/**
 * 获取报表列表（不需要传enterprise_id，后端从Token获取）
 * @param {Object} params - { page_no, page_size }
 * @returns {Promise<Array>} 报表列表
 */
export const fetchReportList = async (params = {}) => {
  try {
    const response = await apiClient.get('/reports', { params });
    return response.data.data || [];
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取报表列表失败');
  }
};

export const fetchReportById = async (id) => {
  try {
    const response = await apiClient.get(`/report/get/${id}`);
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取报表详情失败');
  }
};

/**
 * 获取当前可填报的调查期列表
 * @returns {Promise<Object>} { periods: [], count: number }
 */
export const fetchCurrentPeriods = async () => {
  try {
    const response = await apiClient.get('/periods/current');
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取调查期失败');
  }
};

/**
 * 获取审核历史
 * @param {Object} params - { reporting_period: 'YYYY-MM' }
 * @returns {Promise<Object>} { audit_history: [], count: number }
 */
export const fetchAuditHistory = async (params) => {
  try {
    const response = await apiClient.get('/report/audit-history', { params });
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取审核历史失败');
  }
};

export const fetchReportHistory = async (params) => {
  try {
    const response = await apiClient.get('/report/history', { params });
    return response.data.data || [];
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取报表历史失败');
  }
};

/**
 * 驳回后重新提交
 * @param {Object} data - 报表表单数据
 * @returns {Promise<Object>}
 */
export const resubmitReport = async (data) => {
  try {
    // 自动生成幂等键
    const idempotencyKey = generateUUID();
    const response = await apiClient.post('/report/resubmit', data, {
      headers: {
        'Idempotency-Key': idempotencyKey,
      },
    });
    return response.data.data;
  } catch (error) {
    throw new Error(error.response?.data?.message || '重新提交失败');
  }
};

/**
 * 获取就业人数趋势数据
 * @returns {Promise<Array>}
 */
export const fetchEmploymentTrend = async () => {
  try {
    const response = await apiClient.get('/report/trend');
    return response.data.data || [];
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取趋势数据失败');
  }
};
